import json
import tkinter as tk
from tkinter import ttk, messagebox, filedialog

class JSONParserApp:
    def __init__(self, root):
        self.root = root
        self.root.title("JSON 解析工具")

        # 设置默认窗口大小和位置
        self.set_window_geometry()

        # 创建菜单栏
        self.menu_bar = tk.Menu(root)
        self.root.config(menu=self.menu_bar)

        # 文件菜单
        self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.menu_bar.add_cascade(label="文件", menu=self.file_menu)
        self.file_menu.add_command(label="退出", command=root.quit)

        # 创建输入框
        self.input_label = tk.Label(root, text="输入JSON字符串:")
        self.input_label.grid(row=0, column=0, columnspan=4, pady=5, sticky="w")

        self.input_text = tk.Text(root, height=10, width=50)
        self.input_text.grid(row=1, column=0, columnspan=4, pady=5, padx=10, sticky="ew")

        # 创建按钮
        self.paste_button = tk.Button(root, text="粘贴", command=self.paste_from_clipboard)
        self.paste_button.grid(row=2, column=0, padx=5, pady=5, sticky="ew")

        self.import_button = tk.Button(root, text="导入JSON文件", command=self.import_json_file)
        self.import_button.grid(row=2, column=1, padx=5, pady=5, sticky="ew")

        self.parse_button = tk.Button(root, text="解析JSON", command=self.parse_json)
        self.parse_button.grid(row=2, column=2, padx=5, pady=5, sticky="ew")

        self.clear_button = tk.Button(root, text="清空", command=self.clear_all)
        self.clear_button.grid(row=2, column=3, padx=5, pady=5, sticky="ew")

        # 创建Treeview来显示解析后的JSON
        self.tree = ttk.Treeview(root, columns=("Value"), show="tree")
        self.tree.grid(row=3, column=0, columnspan=4, pady=10, padx=10, sticky="nsew")

        # 配置网格布局的权重
        for i in range(4):
            root.grid_columnconfigure(i, weight=1)
        root.grid_rowconfigure(1, weight=1)
        root.grid_rowconfigure(3, weight=1)

    def set_window_geometry(self):
        # 设置窗口大小为900x500
        window_width = 900
        window_height = 500

        # 获取屏幕尺寸
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()

        # 计算窗口位置（中间略微偏左和偏上）
        x_position = int((screen_width - window_width) * 0.5)  # 50%偏左
        y_position = int((screen_height - window_height) * 0.1)  # 10%偏上

        # 设置窗口位置和大小
        self.root.geometry(f"{window_width}x{window_height}+{x_position}+{y_position}")

    def parse_json(self):
        # 清空Treeview
        for item in self.tree.get_children():
            self.tree.delete(item)

        # 获取输入的JSON字符串
        json_str = self.input_text.get("1.0", tk.END).strip()

        try:
            # 解析JSON
            json_data = json.loads(json_str)
            self.display_json("", json_data)
        except json.JSONDecodeError as e:
            messagebox.showerror("错误", f"无效的JSON格式: {e}")

    def display_json(self, parent, data):
        if isinstance(data, dict):
            for key, value in data.items():
                node = self.tree.insert(parent, "end", text=key)
                self.display_json(node, value)
        elif isinstance(data, list):
            for index, value in enumerate(data):
                node = self.tree.insert(parent, "end", text=f"[{index}]")
                self.display_json(node, value)
        else:
            self.tree.insert(parent, "end", text=str(data))

    def paste_from_clipboard(self):
        try:
            # 获取剪贴板内容
            clipboard_content = self.root.clipboard_get()
            # 清空输入框并插入剪贴板内容
            self.input_text.delete("1.0", tk.END)
            self.input_text.insert("1.0", clipboard_content)
        except tk.TclError:
            messagebox.showwarning("警告", "剪贴板为空或内容不可用")

    def clear_all(self):
        # 清空输入框
        self.input_text.delete("1.0", tk.END)
        # 清空Treeview
        for item in self.tree.get_children():
            self.tree.delete(item)

    def import_json_file(self):
        # 打开文件对话框选择JSON文件
        file_path = filedialog.askopenfilename(filetypes=[("JSON文件", "*.json")])
        if file_path:
            try:
                with open(file_path, "r", encoding="utf-8") as file:
                    json_data = file.read()
                    # 将文件内容填充到输入框
                    self.input_text.delete("1.0", tk.END)
                    self.input_text.insert("1.0", json_data)
            except Exception as e:
                messagebox.showerror("错误", f"无法读取文件: {e}")

if __name__ == "__main__":
    root = tk.Tk()
    app = JSONParserApp(root)
    root.mainloop()